package com.eclink.asset.asset.handler;


import com.alibaba.fastjson.JSON;
import com.eclink.asset.asset.domain.dao.AssetApplyRelItem;
import com.eclink.asset.asset.domain.dao.AssetItem;
import com.eclink.asset.asset.domain.dao.FlowApply;
import com.eclink.asset.asset.domain.form.ApplyFormDataZCPF;

import com.eclink.asset.asset.service.AssetItemService;
import com.eclink.asset.enums.ApplyStateEnum;
import com.eclink.asset.enums.AssetItemStateEnum;
import com.eclink.asset.workflow.mapper.FlowApplyMapper;
import com.eclink.asset.workflow.handler.ApplyFinishHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class AssetApplyDispatchHandler implements ApplyFinishHandler {

    @Resource
    private FlowApplyMapper flowApplyMapper;

    @Resource
    private AssetItemService assetItemService;

    @Transactional
    public void execute(String id) {
        FlowApply flowApply = flowApplyMapper.selectById(id);
        flowApply.setUpdateTime(LocalDateTime.now());
        flowApply.setState(ApplyStateEnum.APPROVED.getValue());
        flowApplyMapper.updateById(flowApply);

        ApplyFormDataZCPF formData = JSON.parseObject(flowApply.getFormData(), ApplyFormDataZCPF.class);

        List<AssetApplyRelItem> items = formData.getItems();
        for (AssetApplyRelItem item : items) {
            AssetItem assetItem = assetItemService.selectById(item.getSourceId());
            assetItem.setState(AssetItemStateEnum.USING.getValue());
            assetItem.setUserId(formData.getTargetUserId());
            assetItemService.update(assetItem);
        }
    }

    @Override
    public void reject(String id) {

    }

}
